﻿namespace etracks.Helpers
{
    using etracks.EntityModels;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Mvc;

    /// <summary>
    /// Extensions for the following types:
    /// String
    /// ControllerBase 
    /// </summary>

    public class DatabaseAuthorizationAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(typeof(DatabaseAuthorizationAttribute));

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            string username = string.Empty;
            string controllerName = string.Empty;
            string actionName = string.Empty;
            string httpMethod = filterContext.HttpContext.Request.HttpMethod;

            if ((filterContext.HttpContext.User != null) 
                && (filterContext.HttpContext.User.Identity != null)
                && (filterContext.HttpContext.User.Identity.IsAuthenticated))
                username = filterContext.HttpContext.User.Identity.Name;
            else
                username = "unauthenticated";

            if (filterContext.ActionDescriptor != null)
            {
                actionName = filterContext.ActionDescriptor.ActionName;

                if (filterContext.ActionDescriptor.ControllerDescriptor != null)
                    controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            }

            log.Error(string.Format(
                "User {0} {1} controller {2}, action {3}",
                username, 
                httpMethod,
                controllerName, 
                actionName));
            
             //Retrieve filter attributes for action and controller
             //filterContext.ActionDescriptor.GetFilterAttributes(false)
             //filterContext.ActionDescriptor.ControllerDescriptor.GetFilterAttributes(false);
            
        }
    }
}
